package com.coolingme.dynamicproxy.cglibproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGlib媒婆
 * <p>
 * 它是通过动态继承目标对象实现动态代理的
 *
 * @author wangyue
 * @date 2020/9/30 15:40
 */
public class CGlibMatchMaker implements MethodInterceptor {

    /**
     * @param clazz
     * @return
     */
    public Object getInstance(Class<?> clazz) {
        //相当于Proxy，代理的工具类
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        this.before();
        Object o = proxy.invokeSuper(obj, args);
        this.after(obj);
        return o;
    }

    private void before() {
        System.out.println("--------------------------------------");
        System.out.println("媒婆开始咨询");
    }

    private void after(Object target) {
        System.out.println(target.getClass().getName());
        if (target instanceof PoolMan) {
            System.out.println("媒婆：爪巴!");
        } else if (target instanceof RichMan) {
            System.out.println("媒婆：彳亍!");
        } else {
            System.out.println("媒婆：安排!");
        }
    }

}
